// 用户管理页面
import React, { useRef, useState } from "react";

import { Table, Space, Button, Form, Input, Popconfirm, message, Select, Modal } from "antd";
import type { TableColumnsType, TableProps } from "antd";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { useAntdTable } from "ahooks";

import api from "../../api/user";
import { IUser, IEditUser } from "../../types/user";
import { formatDateTime } from "../../utils";
import CreateDept from "./CreateUser";
import SearchForm from "../../components/SearchForm";
import AuthButton from "../../components/AuthButton";

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];



const Role: React.FC = () => {
    const deptRef = useRef<{
        showModal: (
            type: string,
            data?: { _id: string } | IUser,
        ) => void,
        upData: () => void
    }>(null); // 定义ref类型
    const columns: TableColumnsType<IUser> = [
        {
            title: "用户ID",
            dataIndex: "userId",
            key: "userId",
        },
        {
            title: "用户名称",
            dataIndex: "userName",
            key: "userName",
        },
        {
            title: "用户邮箱",
            dataIndex: "userEmail",
            key: "userEmail",
        },
        {
            title: "用户角色",
            dataIndex: "role",
            key: "role",
            render: (text: number) => {
                switch (text) {
                    case 0:
                        return '超级管理员';
                    case 1:
                        return '管理员';
                    case 2:
                        return '体验管理员';
                    case 3:
                        return '普通用户';
                    default:
                        return '未知';

                }
            },
        },
        {
            title: "用户状态",
            dataIndex: "state",
            key: "state",
            render: (text: number) => {
                switch (text) {
                    case 1:
                        return '在职';
                    case 2:
                        return '离职';
                    case 3:
                        return '试用期';
                    default:
                        return '未知';

                }
            },
        },
        // 注册时间
        {
            title: "注册时间",
            dataIndex: "createTime",
            key: "createTime",
            render: (text: string) => formatDateTime(new Date(text)),
        },
        // 操作
        {
            title: "操作",
            key: "action",
            render: (_, record: IUser) => (
                <Space>
                    <Button type="text" onClick={
                        () => handleAdd(record)
                    }>编辑</Button>
                    <Popconfirm
                        title={`确定删除${record.userName}吗?`}
                        onConfirm={() => handleDelete([record.userId])}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="text" danger>删除</Button>
                    </Popconfirm>
                </Space>
            )
        }
    ];

    const { confirm } = Modal;
    const [form] = Form.useForm();
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

    const onSelectChange = (_: React.Key[], selectedRows: IUser[]) => {
        setSelectedRowKeys(selectedRows.map(item => item.userId));
    };

    const getTableData = ({ current, pageSize }: { current: number, pageSize: number }, form: IEditUser) => {
        // 获取用户数据
        return api.getUserList({ ...form, pageNum: current, pageSize }).then(res => {
            return {
                total: res.page.total,
                list: res.list
            }
        });
    };
    const { tableProps, search } = useAntdTable(getTableData, {
        form, // 绑定 Ant Design Form
        defaultPageSize: 5,
    });
    // 编辑
    const handleAdd = (record: IUser) => {
        deptRef.current?.showModal('edit', record);
    }
    // 删除
    const handleDelete = (id: number[]) => {

        api.deleteUser({ userIds: id }).then(() => {
            message.success('删除成功');
            // 取消id选中的
            setSelectedRowKeys(selectedRowKeys.filter(item => !id.includes(item)))
            search.submit();
        })

    }
    // 批量删除弹窗
    const handleDeleteAll = () => {
        if (selectedRowKeys.length === 0) return message.error('请选择要删除的项');
        confirm({
            title: '删除确认',
            icon: <ExclamationCircleFilled />,
            content: '确认删除该批用户吗？',
            okText: '确认',
            okType: 'primary',
            cancelText: '取消',
            onOk() {
                handleDelete(selectedRowKeys)
            }
        });
    }
    // 新增
    const handleCreate = () => {
        deptRef.current?.showModal('add');
    }
    const rowSelection: TableRowSelection<IUser> = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    return (
        <div>
            <SearchForm form={form} submit={search.submit} reset={search.reset} >
                <Form.Item name="userId" label="用户ID">
                    <Input placeholder="请输入用户ID" />
                </Form.Item>
                <Form.Item name="userName" label="用户名称">
                    <Input placeholder="请输入用户名称" />
                </Form.Item>
                <Form.Item name="state" label="状态">
                    <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
                        <Select.Option value={0}>所有</Select.Option>
                        <Select.Option value={1}>在职</Select.Option>
                        <Select.Option value={2}>离职</Select.Option>
                        <Select.Option value={3}>试用期</Select.Option>
                    </Select>
                </Form.Item>
            </SearchForm>
            <div className="wrap-table">
                <div className="header">
                    <div className="title">用户列表</div>
                    <div className="action">
                        {/* <Button type="primary" onClick={handleCreate}>新增</Button> */}
                        <AuthButton auth="user@create" type="primary" onClick={handleCreate} >
                            新增
                        </AuthButton>
                        <Button type="primary" danger onClick={handleDeleteAll}>批量删除</Button>
                    </div>
                </div>
                <Table rowKey={'userId'} rowSelection={rowSelection} columns={columns} {...tableProps} />
            </div>
            <CreateDept deptRef={deptRef} upData={search.submit} /> {/* 传递ref */}
        </div>
    );
};

export default Role;
